#coding:utf-8


_bin = ['0000', '0001', '0010', '0011',
        '0100', '0101', '0110', '0111',
        '1000', '1001', '1010', '1011',
        '1100', '1101', '1110', '1111',]

#车台校验和算法
def getchecksum(data):
    """ getchecksum_vehicle38_str(data)==> int\n
        
        Get the Checksum of data between Vehicle and Device,\n
        Used to send data or check received data.\n
        
    """
    checksum = 0
    for number in data:
        checksum += number
        if checksum > 0xff:
            checksum -= 0xff
    if checksum == 0: checksum = 0x7f
    return checksum

#车台末尾校验码(数字字符串)
def getchecksum_buss(data):
    """接收业务数据字符串,返回计算得到的校验和字符串"""
    checksum = int()
    for number in data:
        checksum += number
        if checksum > 0xff:
            checksum -= 0xff
    if checksum >= 0x80: checksum -= 0x80
    if checksum == 0x00: checksum = 0x7f
    return checksum

# 添加7e头尾
def add7e(data):
    if not 0x7e in data:
        return [0x7e]+data+[0x7e]
    else:
        write_event('要发送的数据中包含了"7e"项:%s'%data)
        return data

# 除掉7e头尾
def remove7e(data):
    assert isinstance(data, list)
    if (data.count(0x7e)%2) != 0:
        """异常数据"""
    else:
        datas = []
        _from = _to = 0
        for i in range(data.count(0x7e)/2):
            if data[_from] != 0x7e:
                """异常数据"""
            else:
                _to = data.index(0x7e, _from+1)
                datas.append(data[_from + 1 : _to])
                _from = _to + 1
        return datas
        
#ASCII码转义为16进制
def asc2data(asc_str):
    data = []
    for i in asc_str:
        data.append(ord(i))
    return data
        
#16进制转化为ASCII码
def data2asc(hexdata):
    asc_str = ""
    for i in hexdata:
        asc_str += chr(i)
    return asc_str.strip()

#16进制转化为Unicode字符
def data2unicode(data):
    hexdata = data2hex(data)
    return hexdata.decode('gbk')
    
#16进制转化为Unicode字符
def unicode2data(unistr):
    hexdata = unistr.encode('gbk')
    return hex2data(hexdata)


# 数据转化为数字
def data2num(data):
    num = 0
    m = len(data)
    for i in range(m):
        num = (256**(m-i-1))*data[i] + num
    return num

# 数字转化为数组
def num2data(num):
    data = []
    while True:
        data.insert(0, num%256)
        num  = num / 256
        if num == 0:
            break
    return data


# 从一个数字中抽取一部分
def extract(value, begin, end):
    de = value >> (7- end)
    return de & (2**(end-begin+1)-1)

# 将一个值插入到一个数字中
def insert(value, inserted, begin, end):
    inserted = inserted *(2**(7-end))
    de = 0xff -2**(8-begin) + 2**(7-end)
    return value & de | inserted



# 对一个序列的包装
def pickUps(data):
    if data is None: data=[]
    if isinstance(data, (str, unicode)):
        data = str2data(data)
    assert isinstance(data, list), "list or string:%s"%data
    class _Data:
        def __init__(self, data=[]):
            self._data = data
            self._cursor = 0
        def get(self, nums = 1):
            kids = self._data[self._cursor:self._cursor+nums]
            self._cursor = self._cursor + nums
            if len(kids) == 1:
                return kids[0]
            else:
                return kids
        def waste(self, nums = 1):
            self._cursor = self._cursor + nums
            return self
        def set(self, *args):
            for value in args:
                if isinstance(value, list):
                    self._data = self._data + value
                else:
                    self._data.append(value)   
        def out(self):
            return self._data
    return _Data(data)

#对一个字节的包装  
def pickUp(value = 0x0):
    assert isinstance(value, int)
    assert value >= 0x0 and value <= 0xff
    class _Value:
        def __init__(self, value):
            self.value = value
        def get(self, begin, end):
            return extract(self.value, begin, end)
        def set(self, value, begin, end):
            self.value = insert(self.value, value, begin, end)
        def out(self):
            return self.value
    return _Value(value)

#
def name2data(name):
    return [int(name[:2], 16), int(name[2:], 16)]

def data2name(data):
    return "%02x%02x"%(data[0], data[1])

# 二进制字符串转为文本字符串,显示用
def hex2str(hexstr):
    l = [character.encode('hex') for character in hexstr]
    return ' '.join(l)

# 二进制字符串转为数据序列,操作用
def hex2data(hexstr):
    return [ord(character) for character in hexstr]
    
# 文本字符串转为数据序列,操作用
def str2data(logstr):
    l = logstr.split(' ')
    return [int(i, 16) for i in l]

# 数据序列转为文本字符串,显示用
def data2str(data):
    logstr = ''
    for i in data:
        logstr += '%02x '%i
    return logstr.strip()

# 文本字符串转为二进制字符串,发送/接收数据用
def str2hex(logstr):
    l = logstr.split(" ")
    s = ''
    for character in l:
        s += character.decode('hex')
    return s

# 数据序列转为二进制字符串,发送/接收数据用
def data2hex(data):
    s= ''
    for number in data:
        s += chr(number)
    return s

# 转义字符,7e转为7d+02, 7d转为7d+01
def transform(data):
    l = []
    for number in data:
        if number == 0x7d:
            l += [0x7d, 0x01]
        elif number == 0x7e:
            l += [0x7d, 0x02]
        else:
            l.append(number)
    return l

# 逆转义字符,7d+01转为7d,7d+02转为7e
def untransform(data):
    l = []
    has7d = False
    for number in data:
        if number == 0x7d:
            has7d = True
        else:
            if has7d:
                if number == 0x01:
                    l.append(0x7d)
                elif number == 0x02:
                    l.append(0x7e)
                else:
                    """错误,单独的0x7d存在"""
                    l.append(0x7d)
                    l.append(number)
            else:
                l.append(number)
            has7d = False
    if has7d:
        """错误,单独的0x7d存在"""
    return l
        

def getKey(dict, value):
    for i in dict.items():
        if i[1] == value:
            return i[0]
    else:
        return None

#数据x转八
def code_x_to_8(data, code):
    de = ''
    for i in data:
        de += (_bin[i/16] + _bin[i%16])[8-code:]
    if not de: return []
    de = de.rstrip('0')
    lst = []
    for i in range(len(de) / 8 + 1):
        lst.append(de[i * 8 :i * 8 + 8])
        
    #最后一个值需要补0
    lst[-1] = (lst[-1] + '0' * 8 )[:8]
        
    return [int(i,2) for i in lst]
    
#数据八转X
def code_8_to_x(data, code):
    de = ''
    for i in data:
        de += _bin[i/16] + _bin[i%16]
    if not de: return []
    lst = []
    for i in range(len(de) / code + 1):
        lst.append(de[i * code :i * code + code])
    
    #最后一个值需要补0
    lst[-1] = (lst[-1] + '0' * code )[:code]
    return [int(i, 2) for i in lst]


if __name__ == '__main__':
    c = 1234565462342342
    x = num2data(c)
    print 'x', x
    y = data2num(x)
    print 'y', y
    print data2num(x)-c
